"""
AI视频生成器模块
基于MCP平台实现AI视频生成功能
"""

import asyncio
import json
import logging
import time
from pathlib import Path
from typing import Dict, Optional

import aiohttp
import yaml


class AIVideoGenerator:
    """AI视频生成器"""
    
    def __init__(self, config_path: str = "config.yaml"):
        """
        初始化AI视频生成器
        
        Args:
            config_path: 配置文件路径
        """
        self.config = self._load_config(config_path)
        self.logger = logging.getLogger(__name__)
        self.session: Optional[aiohttp.ClientSession] = None
        
    def _load_config(self, config_path: str) -> Dict:
        """加载配置文件"""
        with open(config_path, 'r', encoding='utf-8') as f:
            return yaml.safe_load(f)
    
    async def __aenter__(self):
        """异步上下文管理器入口"""
        self.session = aiohttp.ClientSession(
            timeout=aiohttp.ClientTimeout(total=self.config['ai_video']['mcp']['timeout'])
        )
        return self
    
    async def __aexit__(self, exc_type, exc_val, exc_tb):
        """异步上下文管理器出口"""
        if self.session:
            await self.session.close()
    
    async def generate_video(self, text: str, output_path: Optional[str] = None) -> str:
        """
        生成AI视频
        
        Args:
            text: 视频文案
            output_path: 输出文件路径
            
        Returns:
            生成的视频文件路径
        """
        if not self.session:
            raise RuntimeError("请使用异步上下文管理器")
        
        self.logger.info(f"开始生成视频，文案长度: {len(text)} 字符")
        
        # 准备请求数据
        request_data = {
            "text": text,
            "model": self.config['ai_video']['generation']['model'],
            "resolution": self.config['ai_video']['generation']['resolution'],
            "duration": self.config['ai_video']['generation']['duration'],
            "fps": self.config['ai_video']['generation']['fps'],
            "format": self.config['ai_video']['generation']['format'],
            "style": self.config['ai_video']['default_params']['style'],
            "voice": self.config['ai_video']['default_params']['voice'],
            "background_music": self.config['ai_video']['default_params']['background_music']
        }
        
        # 调用MCP API
        video_url = await self._call_mcp_api(request_data)
        
        # 下载视频文件
        if not output_path:
            output_dir = Path(self.config['paths']['output_dir'])
            output_dir.mkdir(exist_ok=True)
            timestamp = int(time.time())
            output_path = str(output_dir / f"ai_video_{timestamp}.mp4")
        
        await self._download_video(video_url, output_path)
        
        self.logger.info(f"视频生成完成: {output_path}")
        return output_path
    
    async def _call_mcp_api(self, request_data: Dict) -> str:
        """调用MCP API生成视频"""
        mcp_config = self.config['ai_video']['mcp']
        url = f"{mcp_config['base_url']}/video/generate"
        
        headers = {
            "Authorization": f"Bearer {mcp_config['api_key']}",
            "Content-Type": "application/json"
        }
        
        max_retries = self.config['app']['max_retries']
        retry_delay = self.config['app']['retry_delay']
        
        for attempt in range(max_retries):
            try:
                async with self.session.post(url, json=request_data, headers=headers) as response:
                    if response.status == 200:
                        result = await response.json()
                        if result.get('success'):
                            return result['data']['video_url']
                        else:
                            raise Exception(f"API返回错误: {result.get('message', 'Unknown error')}")
                    else:
                        raise Exception(f"HTTP错误: {response.status}")
                        
            except Exception as e:
                self.logger.warning(f"API调用失败 (尝试 {attempt + 1}/{max_retries}): {e}")
                if attempt == max_retries - 1:
                    raise
                await asyncio.sleep(retry_delay)
    
    async def _download_video(self, video_url: str, output_path: str):
        """下载视频文件"""
        try:
            async with self.session.get(video_url) as response:
                if response.status == 200:
                    with open(output_path, 'wb') as f:
                        async for chunk in response.content.iter_chunked(1024):
                            f.write(chunk)
                else:
                    raise Exception(f"下载失败: {response.status}")
        except Exception as e:
            self.logger.error(f"视频下载失败: {e}")
            raise


def generate_video_sync(text: str, config_path: str = "config.yaml") -> str:
    """
    同步版本的视频生成函数
    
    Args:
        text: 视频文案
        config_path: 配置文件路径
        
    Returns:
        生成的视频文件路径
    """
    async def _generate():
        async with AIVideoGenerator(config_path) as generator:
            return await generator.generate_video(text)
    
    return asyncio.run(_generate())